<template>
  <div class="contract-form">
    <!-- 基本信息 -->
    <h3>基本信息</h3>
    <el-form :model="form" :rules="rules" ref="contractForm" label-width="80px" class="basic-info">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="所属小区" prop="communityId">
            <el-select v-model="form.communityId" placeholder="请选择小区" style="width: 100%;"
              @change="handleCommunityChange" clearable>
              <el-option v-for="item in communityOptions" :key="item.id" :label="item.communityName"
                :value="item.communityId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="车位号" prop="parkingSpaceId">
            <el-select v-model="form.parkingSpaceId" placeholder="请选择车位号" style="width: 100%;"
              @change="handleParkingSpaceChange" clearable :disabled="!form.communityId">
              <el-option v-for="item in parkingSpaceOptions" :key="item.id" :label="item.parkingSpaceCode"
                :value="item.parkingSpaceId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收费金额">
            <el-input v-model="feeAmount" disabled style="width: 100%;" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="租赁方" prop="leaseCompany">
            <el-input v-model="form.leaseCompany" placeholder="请输入租赁方" style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系人" prop="leaseName">
            <el-input v-model="form.leaseName" placeholder="请输入租赁方联系人" style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系电话" prop="leasePhone">
            <el-input v-model="form.leasePhone" placeholder="请输入租赁方联系人电话" style="width: 100%;" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="车辆号码" prop="vehicleLicense">
            <el-input v-model="form.vehicleLicense" placeholder="请输入车牌号" style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="车辆排量" prop="vehicleDisplacement">
            <el-input v-model="form.vehicleDisplacement" placeholder="请输入车辆排量" style="width: 100%;" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 合同信息 -->
    <h3>合同信息</h3>
    <el-form :model="form" :rules="rules" ref="contractForm" label-width="80px" class="contract-info">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="合同编号" prop="contractNumber">
            <el-input v-model="form.contractNumber" placeholder="请输入" style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="租户" prop="tenantName">
            <el-input v-model="form.tenantName" placeholder="请输入" style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="签订日期" prop="signingDate">
            <el-date-picker v-model="form.signingDate" type="date" placeholder="请选择时间" style="width: 100%;" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="法定代表" prop="legalRepresentative">
            <el-input v-model="form.legalRepresentative" placeholder="请输入" style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="租户电话" prop="tenantPhone">
            <el-input v-model="form.tenantPhone" placeholder="请输入" style="width: 100%;" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="租期(月)" prop="leaseTerm">
            <el-input v-model.number="form.leaseTerm" placeholder="请输入" style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="停租日期" prop="stopDate">
            <el-date-picker v-model="form.stopDate" type="date" placeholder="请选择时间" style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="起租日期" prop="startDate">
            <el-date-picker v-model="form.startDate" type="date" placeholder="请选择时间" style="width: 100%;" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="收费面积" prop="collectionArea">
            <el-input v-model.number="form.collectionArea" placeholder="请输入" style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="押金">
            <el-input v-model="brokerage" placeholder="0" disabled style="width: 100%;" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="租金方式" prop="depositId">
            <el-select v-model="form.depositId" placeholder="请选择租金方式" @change="handleRentWayChange"
              style="width: 100%;">
              <el-option v-for="item in depositOptions" :key="item.depositId" :label="item.depositName"
                :value="item.depositId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同总额">
            <el-input v-model="TotalAmount" disabled style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="押金说明" prop="depositDescription">
            <el-input v-model="form.depositDescription" placeholder="请输入" style="width: 100%;" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="form.remarks" placeholder="请输入" style="width: 100%;" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 操作按钮 -->
    <div class="button-group" style="text-align: right;margin-right: 30px;">
      <el-button type="primary" @click="handleSave" :loading="loading">提交</el-button>
      <el-button @click="goBack">取消</el-button>
    </div>
  </div>
</template>

<script>
import request, { communityRequest } from '@/utils/request';

export default {
  name: 'ContractForm',
  data() {
    // 自定义验证规则
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入联系电话'));
      }
      if (!/^1[3-9]\d{9}$/.test(value)) {
        return callback(new Error('请输入正确的手机号码'));
      }
      callback();
    };

    const validateCarNumber = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入车牌号'));
      }
      callback();
    };

    const validateDate = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请选择日期'));
      }
      callback();
    };

    return {
      feeAmount: 0,
      brokerage: 0,
      TotalAmount: 0,
      loading: false,
      form: {
        communityId: "",
        depositId: 1,
        contractNumber: "",
        leaseCompany: "",
        leaseName: "",
        leasePhone: "",
        tenantName: "",
        tenantPhone: "",
        legalRepresentative: "",
        collectionArea: "",
        signingDate: "",
        leaseTerm: 1,
        startDate: "",
        stopDate: "",
        depositDescription: "",
        remarks: "",
        parkingSpaceId: "",
        vehicleLicense: "",
        vehicleDisplacement: ""
      },
      communityOptions: [],
      parkingSpaceOptions: [],
      depositOptions: [],
      rules: {
        communityId: [{ required: true, message: '请选择小区', trigger: 'change' }],
        parkingSpaceId: [{ required: true, message: '请选择车位', trigger: 'change' }],
        leaseCompany: [{ required: true, message: '请输入租赁方', trigger: 'blur' }],
        leaseName: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
        leasePhone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
        vehicleLicense: [{ required: true, validator: validateCarNumber, trigger: 'blur' }],
        vehicleDisplacement: [{ required: true, message: '请输入车辆排量', trigger: 'blur' }],
        contractNumber: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
        tenantName: [{ required: true, message: '请输入租户姓名', trigger: 'blur' }],
        signingDate: [{ required: true, validator: validateDate, trigger: 'change' }],
        legalRepresentative: [{ required: true, message: '请输入法定代表人', trigger: 'blur' }],
        tenantPhone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
        leaseTerm: [
          { required: true, message: '请输入租期', trigger: 'blur' },
          { type: 'number', message: '租期必须为数字', trigger: 'blur' }
        ],
        stopDate: [{ required: true, validator: validateDate, trigger: 'change' }],
        startDate: [{ required: true, validator: validateDate, trigger: 'change' }],
        depositId: [{ required: true, message: '请选择租金方式', trigger: 'change' }],
      },
      showPaymentDialog: false, // 支付状态弹窗
      pollingCount: 0, // 轮询计数
      maxPollingCount: 15 // 最大轮询次数
    }
  },
  created() {
    this.gitCommunity();
    this.getDepositOptions(1);
  },
  watch: {
    'form.leaseTerm': {
      handler(newVal) {
        if (newVal) {
          this.getDepositOptions(newVal);
        }
      },
      immediate: true
    },
    'form.startDate'(newVal) {
      if (newVal && this.form.stopDate) {
        this.validateDateRange();
      }
    },
    'form.stopDate'(newVal) {
      if (newVal && this.form.startDate) {
        this.validateDateRange();
      }
    }
  },
  methods: {
    // 获取小区
    gitCommunity() {
      communityRequest.get('/community/selcomm')
        .then(res => {
          this.communityOptions = res.data || [];
        })
        .catch(err => {
          this.$message.error('获取小区列表失败');
        });
    },

    // 小区选择变化时获取对应车位
    handleCommunityChange(communityId) {
      this.form.parkingSpaceId = '';
      this.feeAmount = 0;
      this.parkingSpaceOptions = [];

      if (communityId) {
        this.form.communityId = communityId;
        this.getParkingSpace(communityId);
      }
    },

    // 获取小区对应的车位
    getParkingSpace(communityId) {
      request.get(`/parkingSpace/byidlist?commId=${communityId}`)
        .then(res => {
          this.parkingSpaceOptions = res.data || [];
        })
        .catch(err => {
          this.$message.error('获取车位列表失败');
        });
    },

    // 车位选择变化时获取收费金额
    handleParkingSpaceChange(parkingSpaceId) {
      this.feeAmount = 0;
      if (parkingSpaceId) {
        this.form.parkingSpaceId = parkingSpaceId;
        this.getFeeAmount(parkingSpaceId);
        this.getTotalAmount(parkingSpaceId);
      }
    },

    // 根据车位获取收费金额
    getFeeAmount(parkingSpaceId) {
      request.get(`/parkingLease/getPricingByParkingSpaceId?spaceId=${parkingSpaceId}`)
        .then(res => {
          this.feeAmount = res.data.price || 0;
          this.brokerage = this.feeAmount;
          this.form.collectionArea = res.data.pricingSpaceArea;
        })
        .catch(err => {
          this.$message.error('获取收费金额失败');
        });
    },

    // 获取租金方式
    getDepositOptions(leaseTerm) {
      request.get(`/deposit/getLeaseDeposit/${leaseTerm}`)
        .then(res => {
          this.depositOptions = res.data || [];
        })
        .catch(err => {
          this.$message.error('获取租金方式失败');
        });
    },

    // 租金方式变化时处理
    handleRentWayChange(depositId) {
      this.form.depositId = depositId;
      if (this.form.parkingSpaceId) {
        this.getTotalAmount(this.form.parkingSpaceId);
      }
    },

    // 获取总金额
    getTotalAmount(parkingSpaceId) {
      request.post('/parkingLease/getParkingLeaseAutoMoney', {
        leaseTerm: this.form.leaseTerm,
        depositId: this.form.depositId,
        parkingSpaceId: parkingSpaceId,
      })
        .then(res => {
          this.TotalAmount = res.data.TotalAmount || 0;
        })
        .catch(err => {
          this.$message.error('获取总金额失败');
        });
    },

    // 验证日期范围
    validateDateRange() {
      if (new Date(this.form.stopDate) < new Date(this.form.startDate)) {
        this.$message.warning('停租日期不能早于起租日期');
        this.form.stopDate = '';
      }
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`;
    },

    // 返回上一页
    goBack() {
      this.$router.go(-1);
    },
    async handleSave() {
      try {
        // 表单验证
        const valid = await this.$refs.contractForm.validate();
        if (!valid) {
          this.$message.error('请完善表单信息');
          return;
        }

        this.loading = true;

        // 构造提交数据
        const submitData = {
          ...this.form,
          signingDate: this.formatDate(this.form.signingDate),
          startDate: this.formatDate(this.form.startDate),
          stopDate: this.formatDate(this.form.stopDate),
          price: this.feeAmount,
          totalAmount: this.TotalAmount
        };

        // 提交表单到车位租赁接口
        const res = await request.post('/parkingLease/addParkingLease', submitData);

        if (res.code === 200 && res.data) {
          const billId = res.data.billId;

          // 打开新窗口进行支付
          const payWindow = window.open('', '_blank');

          try {
            // 获取支付页面HTML，添加type参数区分车位租赁
            const payRes = await request.post(`/billPay/payOrder`, {
              billId: billId,
              type: 'parking' // 添加支付类型标识
            });

            // 写入新窗口
            payWindow.document.write(payRes.data);
            payWindow.document.close();

            // 开始轮询支付状态
            this.startPaymentPolling(billId);

          } catch (err) {
            payWindow.close();
            this.$message.error('打开支付页面失败');
            console.error(err);
          }

        } else {
          this.$message.error(res.message || '提交失败');
        }
      } catch (err) {
        this.$message.error('提交过程中发生错误');
        console.error(err);
      } finally {
        this.loading = false;
      }
    },

    // 开始支付状态轮询
    startPaymentPolling(billId) {
      this.showPaymentDialog = true;
      this.pollingCount = 0;
      this.maxPollingCount = 15; // 15次*2秒=30秒超时

      const timer = setInterval(async () => {
        if (this.pollingCount >= this.maxPollingCount) {
          clearInterval(timer);
          this.showPaymentDialog = false;
          this.$message.warning('支付状态检查超时，请手动刷新页面查看支付结果');
          return;
        }

        this.pollingCount++;

        try {
          // 检查支付状态，添加type参数
          const res = await request.get(`/billPay/checkPaymentStatus/${billId}?type=parking`);

          if (res.data === true) {  // 支付成功
            clearInterval(timer);
            this.showPaymentDialog = false;
            this.$message.success('支付成功');
            this.$router.push({
              path: '/payment/success',
              query: {
                billId,
                type: 'parking',
                amount: this.TotalAmount
              }
            });
          } else if (this.pollingCount === this.maxPollingCount) {
            this.$message.warning('支付状态未确认，请稍后查看订单状态');
          }
        } catch (err) {
          console.error('检查支付状态失败', err);
          clearInterval(timer);
          this.showPaymentDialog = false;
        }
      }, 2000);  // 每2秒检查一次
    }

  }
}
</script>

<style scoped>
.contract-form {
  padding: 20px;
}

h3 {
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
}

.basic-info,
.contract-info {
  margin-bottom: 20px;
}

.el-form-item {
  margin-bottom: 15px;
}

.button-group {
  margin-top: 20px;
}
</style>
